<template>
    <div class="notification-center-container">
        <!-- 顶部导航栏 -->
        <header class="header">
            <button class="back-btn" @click="goBack">
                <span class="back-icon">‹</span>
                通知中心
            </button>
        </header>

        <!-- 主要内容 -->
        <main class="main-content">
            <!-- 加载状态 -->
            <div v-if="loading" class="loading-container">
                <div class="loading-spinner"></div>
                <p class="loading-text">正在加载通知...</p>
            </div>

            <!-- 错误提示 -->
            <div v-else-if="errorMessage" class="error-container">
                <div class="error-icon">⚠️</div>
                <p class="error-text">{{ errorMessage }}</p>
                <button class="retry-btn" @click="fetchNotifications">重试</button>
            </div>

            <!-- 通知内容 -->
            <div v-else class="notifications-wrapper">
                <!-- 队伍名称 -->
                <div class="team-name-section">
                    <h2 class="team-name">{{ teamName }}</h2>
                </div>

                <!-- 通知列表 -->
                <div class="notifications-list">
                    <!-- 通知项 -->
                    <div v-for="notification in notifications" :key="notification.id" class="notification-card">
                        <!-- 通知标题和操作 -->
                        <div class="notification-header">
                            <h3 class="notification-title">{{ notification.title }}</h3>

                            <div class="header-actions">
                                <!-- 确认按钮 -->
                                <button
                                    v-if="notification.requireConfirmation && !notification.isConfirmed && !canDelete(notification)"
                                    class="confirm-btn" @click="confirmNotificationDirect(notification.id)">
                                    确认
                                </button>
                                <!-- 已确认状态 -->
                                <span v-if="notification.requireConfirmation && notification.isConfirmed"
                                    class="confirmed-badge">
                                    已确认
                                </span>
                                <!-- 删除按钮 -->
                                <button v-if="canDelete(notification)" class="delete-btn"
                                    @click="showDeleteConfirmDialog(notification.id)">
                                    删除
                                </button>
                            </div>
                        </div>


                        <!-- 通知内容 -->
                        <div class="notification-body">
                            <p class="notification-text">{{ notification.content }}</p>

                            <!-- 通知图片 - 显示所有图片 -->
                            <div v-if="notification.allImages && notification.allImages.length > 0"
                                class="notification-images">
                                <img v-for="(imageUrl, index) in notification.allImages" :key="index" :src="imageUrl"
                                    :alt="`通知图片${index + 1}`" class="notification-image"
                                    @click="previewImage(imageUrl)" />
                            </div>
                            <!-- 确认名单显示 -->
                            <div v-if="notification.requireConfirmation && notification.confirmedMembers && notification.confirmedMembers.length > 0"
                                class="confirmed-members">
                                <span class="confirmed-label">已确认：</span>
                                <span class="confirmed-names">{{ notification.confirmedMembers.join('、') }}</span>
                            </div>
                        </div>
                        <!-- 通知底部信息 -->
                        <div class="notification-footer">
                            <span class="notification-author">发布者：{{ notification.authorName }}</span>
                            <span class="notification-time">{{ formatTime(notification.createTime) }}</span>
                        </div>
                    </div>

                    <!-- 空状态 -->
                    <div v-if="notifications.length === 0" class="empty-state">
                        <div class="empty-icon">📢</div>
                        <p class="empty-text">暂无通知</p>
                    </div>
                </div>

                <!-- 发布通知按钮 -->
                <div v-if="canPublish" class="publish-section">
                    <button class="publish-btn" @click="goToPublish">
                        发布通知
                    </button>
                </div>
            </div>
        </main>



        <!-- 成功提示 -->
        <div v-if="successMessage" class="success-toast">
            <div class="success-icon">✅</div>
            <p class="success-text">{{ successMessage }}</p>
        </div>

        <!-- 错误提示 -->
        <div v-if="errorMessage" class="error-toast">
            <div class="error-icon">❌</div>
            <p class="error-text">{{ errorMessage }}</p>
        </div>

        <!-- 删除确认弹窗 -->
        <div v-if="showDeleteConfirm" class="confirm-overlay" @click="cancelDelete">
            <div class="confirm-dialog" @click.stop>
                <div class="confirm-header">
                    <h3 class="confirm-title">确认删除</h3>
                </div>
                <div class="confirm-body">
                    <p class="confirm-message">确定要删除这条通知吗？</p>
                </div>
                <div class="confirm-footer">
                    <button class="cancel-btn" @click="cancelDelete">取消</button>
                    <button class="confirm-btn" @click="confirmDelete">确定</button>
                </div>
            </div>
        </div>



        <!-- 图片预览弹窗 -->
        <div v-if="previewImageUrl" class="image-preview-overlay" @click="closeImagePreview">
            <div class="image-preview-content" @click.stop>
                <img :src="previewImageUrl" alt="预览图片" class="preview-image" />
                <button class="close-preview-btn" @click="closeImagePreview">×</button>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useStudentStore } from '@/stores/student.js'
import { getTeamNotificationsService, deleteNotificationService, confirmNotificationService, getNotificationDetailService } from '@/api/notification.js'
import { getTeamDetailService } from '@/api/team.js'

const router = useRouter()
const route = useRoute()
const studentStore = useStudentStore()

// 响应式数据
const notifications = ref([])
const teamName = ref('')
const loading = ref(false)
const errorMessage = ref('')
const previewImageUrl = ref('')
const successMessage = ref('')
const showDeleteConfirm = ref(false)
const deleteNotificationId = ref(null)

// 计算属性
const canPublish = computed(() => {
    // 所有人都可以发布通知
    return true
})

// 获取当前用户信息
const getCurrentUserInfo = () => {
    // 这里应该从用户状态管理或本地存储中获取用户信息
    // 暂时使用模拟数据，实际应该从 studentStore 或其他地方获取
    const studentStore = useStudentStore()

    // 假设用户信息存储在 store 中
    const userType = studentStore.userType || 'student' // 'teacher' 或 'student'
    const userId = studentStore.userId || 1
    const userName = studentStore.userName || '当前用户'

    const userTypeCode = userType === 'teacher' ? 1 : 2

    return [userTypeCode, userId, userName]
}

// 判断是否可以删除特定通知
const canDelete = (notification) => {
    // 获取当前用户信息
    const userInfo = getCurrentUserInfo()
    const currentUserType = userInfo[0] // 1=教师, 2=学生
    const currentUserId = userInfo[1]

    // 只能删除自己发布的通知
    return notification.publisherType === currentUserType && notification.publisherId === currentUserId
}

// 获取队伍ID
const teamId = computed(() => route.params.teamId)

// 页面挂载时初始化
onMounted(async () => {
    await fetchTeamInfo()
    await fetchNotifications()
})

// 获取队伍信息
const fetchTeamInfo = async () => {
    try {
        const response = await getTeamDetailService(teamId.value)
        if (response.code === 200 && response.data) {
            teamName.value = response.data.teamName + '队'
        }
        console.log('获取队伍信息成功，队伍ID:', teamId.value, '队伍名称:', teamName.value)
    } catch (error) {
        console.error('获取队伍信息失败:', error)

    }
}

// 获取通知列表
const fetchNotifications = async () => {
    loading.value = true
    errorMessage.value = ''

    try {
        console.log('获取通知列表，队伍ID:', teamId.value)
        const response = await getTeamNotificationsService(teamId.value)

        if (response.code === 200) {
            // 转换后端数据格式为前端需要的格式
            notifications.value = (response.data || []).map(item => ({
                id: item.id,
                title: item.title,
                content: item.contentSummary, // 使用 contentSummary 作为内容显示
                authorName: item.publisherName,
                createTime: item.createTime,
                images: item.firstImageUrl ? [{ url: item.firstImageUrl }] : [], // 列表中只显示第一张图片
                allImages: item.allImages || [], // 保存所有图片URL，用于详情显示
                link: null, // 当前返回数据中没有 link 字段
                imageCount: item.imageCount || 0,
                isConfirmed: item.isConfirmed,
                confirmationProgress: item.confirmationProgress,
                // 确认相关字段
                requireConfirmation: item.requireConfirmation,
                totalMembers: item.totalMembers,
                confirmedCount: item.confirmedCount,
                // 确认成员名单（需要从详情接口获取或后端直接返回）
                confirmedMembers: [], // 暂时为空，后续可以从详情接口获取
                // 发布者信息，用于权限判断
                publisherType: item.publisherType,
                publisherId: item.publisherId,
                // 保存原始数据，用于详情显示
                rawData: item
            }))

            // 获取每个通知的确认名单
            await fetchConfirmedMembers()
            console.log('获取通知列表成功，共', notifications.value.length, '条通知')
        } else {
            errorMessage.value = response.message || '获取通知失败'
        }
    } catch (error) {
        console.error('获取通知失败:', error)
        errorMessage.value = '网络连接异常，请检查网络后重试'
    } finally {
        loading.value = false
    }
}

// 获取确认成员名单
const fetchConfirmedMembers = async () => {
    try {
        // 只获取需要确认且有人确认的通知的成员名单
        const needConfirmNotifications = notifications.value.filter(n =>
            n.requireConfirmation && n.confirmedCount > 0
        )

        for (const notification of needConfirmNotifications) {
            const response = await getNotificationDetailService(notification.id)
            if (response.code === 200 && response.data && response.data.confirmations) {
                notification.confirmedMembers = response.data.confirmations.map(c => c.confirmerName)
            }
        }
    } catch (error) {
        console.error('获取确认成员名单失败:', error)
        // 不显示错误提示，静默失败
    }
}

// 显示删除确认弹窗
const showDeleteConfirmDialog = (notificationId) => {
    deleteNotificationId.value = notificationId
    showDeleteConfirm.value = true
}

// 确认删除通知
const confirmDelete = async () => {
    if (!deleteNotificationId.value) return

    try {
        console.log('删除通知，ID:', deleteNotificationId.value)
        const response = await deleteNotificationService(deleteNotificationId.value)

        if (response.code === 200) {
            notifications.value = notifications.value.filter(n => n.id !== deleteNotificationId.value)
            showSuccess('删除成功')
        } else {
            showError(response.message || '删除失败')
        }
    } catch (error) {
        console.error('删除通知失败:', error)
        showError('删除失败，请稍后重试')
    } finally {
        closeDeleteConfirm()
    }
}

// 取消删除
const cancelDelete = () => {
    closeDeleteConfirm()
}

// 关闭删除确认弹窗
const closeDeleteConfirm = () => {
    showDeleteConfirm.value = false
    deleteNotificationId.value = null
}

// 直接确认通知（不需要弹窗）
const confirmNotificationDirect = async (notificationId) => {
    try {
        const confirmData = {
            notificationId: notificationId,
            remark: null // 简化版本不需要备注
        }

        console.log('直接确认通知，数据:', confirmData)
        const response = await confirmNotificationService(confirmData)

        if (response.code === 200) {
            // 更新本地通知状态
            const notification = notifications.value.find(n => n.id === notificationId)
            if (notification) {
                notification.isConfirmed = true
                notification.confirmedCount += 1
                notification.confirmationProgress = notification.confirmedCount / notification.totalMembers

                // 添加当前用户到确认名单
                const userInfo = getCurrentUserInfo()
                const userName = userInfo[2]
                if (!notification.confirmedMembers) {
                    notification.confirmedMembers = []
                }
                notification.confirmedMembers.push(userName)
            }
            showSuccess('确认成功')
        } else {
            showError(response.message || '确认失败')
        }
    } catch (error) {
        console.error('确认通知失败:', error)
        showError('确认失败，请稍后重试')
    }
}



// 预览图片
const previewImage = (imageUrl) => {
    previewImageUrl.value = imageUrl
}

// 关闭图片预览
const closeImagePreview = () => {
    previewImageUrl.value = ''
}

// 显示成功提示
const showSuccess = (message) => {
    errorMessage.value = ''
    successMessage.value = message
    setTimeout(() => {
        successMessage.value = ''
    }, 3000)
}

// 显示错误提示
const showError = (message) => {
    successMessage.value = ''
    errorMessage.value = message
    setTimeout(() => {
        errorMessage.value = ''
    }, 3000)
}

// 跳转到发布通知页面
const goToPublish = () => {
    router.push({
        name: 'PublishNotification',
        params: { teamId: teamId.value }
    })
}

// 返回上一页
const goBack = () => {
    router.go(-1)
}

// 格式化时间
const formatTime = (timeString) => {
    if (!timeString) return ''
    const date = new Date(timeString)
    const now = new Date()
    const diff = now - date

    // 小于1分钟
    if (diff < 60000) {
        return '刚刚'
    }
    // 小于1小时
    if (diff < 3600000) {
        return `${Math.floor(diff / 60000)}分钟前`
    }
    // 小于1天
    if (diff < 86400000) {
        return `${Math.floor(diff / 3600000)}小时前`
    }
    // 大于1天，显示具体日期
    return `${date.getMonth() + 1}月${date.getDate()}日`
}
</script>

<style scoped lang="scss">
//@import '@/assets/css/notification-center.css';
.notification-center-container {
    min-height: 100vh;
    background: #f5f5f5;
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}

/* 顶部导航栏 */
.header {
    background: #FF8C00;
    padding: 12px 16px;
    display: flex;
    align-items: center;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.back-btn {
    background: none;
    border: none;
    color: white;
    font-size: 18px;
    font-weight: 500;
    cursor: pointer;
    display: flex;
    align-items: center;
    gap: 8px;
}

.back-icon {
    font-size: 24px;
    font-weight: bold;
}

/* 主要内容 */
.main-content {
    padding: 0;
}

/* 加载和错误状态 */
.loading-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 50px 0;
    color: #666;
}

.loading-spinner {
    border: 4px solid #f3f3f3;
    border-top: 4px solid #FF8C00;
    border-radius: 50%;
    width: 40px;
    height: 40px;
    animation: spin 1s linear infinite;
    margin-bottom: 15px;
}

@keyframes spin {
    0% {
        transform: rotate(0deg);
    }

    100% {
        transform: rotate(360deg);
    }
}

.loading-text {
    font-size: 16px;
    color: #666;
}

.error-container {
    text-align: center;
    padding: 50px 20px;
    color: #dc3545;
}

.error-icon {
    font-size: 48px;
    margin-bottom: 15px;
}

.error-text {
    font-size: 16px;
    margin-bottom: 20px;
}

.retry-btn {
    background: #FF8C00;
    color: white;
    border: none;
    padding: 10px 20px;
    border-radius: 6px;
    cursor: pointer;
    font-size: 14px;
}

/* 通知内容区域 */
.notifications-wrapper {
    background: white;
    min-height: calc(100vh - 60px);
}

/* 队伍名称区域 */
.team-name-section {
    padding: 20px 16px;
    border-bottom: 2px solid #b3b3b3;
}

.team-name {
    font-size: 22px;
    font-weight: 600;
    color: #333;
    margin: 0;
}

/* 通知列表 */
.notifications-list {
    padding: 0;
}

.notification-card {
    background: white;
    border-bottom: 8px solid #f5f5f5;
    padding: 16px;
}

.notification-card:last-child {
    border-bottom: none;
}

/* 通知头部 */
.notification-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 12px;
}

.notification-title {
    font-size: 16px;
    font-weight: 600;
    color: #333;
    margin: 0;
    flex: 1;
}

.header-actions {
    display: flex;
    align-items: center;
    gap: 8px;
    flex-shrink: 0;
}

.confirm-btn {
    background: #28a745;
    color: white;
    border: none;
    padding: 6px 12px;
    border-radius: 4px;
    font-size: 12px;
    cursor: pointer;
    transition: background-color 0.3s ease;
}

.confirm-btn:hover {
    background: #218838;
}

.confirmed-badge {
    background: #28a745;
    color: white;
    padding: 4px 8px;
    border-radius: 12px;
    font-size: 11px;
    font-weight: 500;
}

.delete-btn {
    background: #dc3545;
    color: white;
    border: none;
    padding: 6px 12px;
    border-radius: 4px;
    font-size: 12px;
    cursor: pointer;
    transition: background-color 0.3s ease;
}

.delete-btn:hover {
    background: #c82333;
}

/* 通知内容 */
.notification-body {
    margin-bottom: 12px;
    cursor: pointer;
    transition: background-color 0.2s ease;
}

.notification-body:hover {
    /* background: #f8f9fa; */
    border-radius: 6px;
    padding: 8px;
    margin: -8px;
}

.notification-text {
    font-size: 14px;
    color: #333;
    line-height: 1.5;
    margin: 0 0 12px 0;
    white-space: pre-wrap;
}



/* 通知链接 */
.notification-link {
    margin: 12px 0;
    padding: 8px 12px;
    background: #f8f9fa;
    border-radius: 4px;
    border-left: 3px solid #FF8C00;
}

.link-url {
    color: #007bff;
    text-decoration: none;
    font-size: 14px;
    word-break: break-all;
}

.link-url:hover {
    text-decoration: underline;
}

/* 通知图片 */
.notification-images {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
    gap: 8px;
    margin: 12px 0;
}

.notification-image {
    width: 100%;
    height: 120px;
    border-radius: 4px;
    cursor: pointer;
    transition: transform 0.2s ease;
    object-fit: cover;
}

.notification-image:hover {
    transform: scale(1.05);
}

/* 通知底部信息 */
/* 确认成员名单 */
.confirmed-members {
    margin: 12px 0;
    padding: 8px 12px;
    background: #f0f8f0;
    border-radius: 6px;
    border-left: 4px solid #28a745;
}

.confirmed-label {
    font-size: 13px;
    color: #28a745;
    font-weight: 500;
}

.confirmed-names {
    font-size: 13px;
    color: #333;
    margin-left: 4px;
}

.notification-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 12px;
    color: #999;
    padding-top: 8px;
    border-top: 1px solid #f0f0f0;
}

.notification-author {
    color: #666;
}

.notification-time {
    color: #999;
}



/* 空状态 */
.empty-state {
    text-align: center;
    padding: 60px 20px;
    color: #999;
}

.empty-icon {
    font-size: 48px;
    margin-bottom: 16px;
}

.empty-text {
    font-size: 16px;
    margin: 0;
}

/* 发布通知按钮 */
.publish-section {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    padding: 16px;
    background: white;
    border-top: 1px solid #e5e5e5;
}

.publish-btn {
    width: 100%;
    color: white;
    border: none;
    padding: 14px;
    background: #007bff;
    border-radius: 6px;
    font-size: 16px;
    font-weight: 500;
    cursor: pointer;
    transition: background-color 0.3s ease;
}

.publish-btn:hover {
    background: #0056b3;
}

/* 图片预览弹窗 */
.image-preview-overlay {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.8);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 9999;
    animation: fadeIn 0.3s ease-out;
}

@keyframes fadeIn {
    from {
        opacity: 0;
    }

    to {
        opacity: 1;
    }
}

.image-preview-content {
    position: relative;
    max-width: 90%;
    max-height: 90%;
}

.preview-image {
    max-width: 100%;
    max-height: 100%;
    border-radius: 8px;
}

.close-preview-btn {
    position: absolute;
    top: -40px;
    right: 0;
    background: none;
    border: none;
    color: white;
    font-size: 30px;
    cursor: pointer;
    width: 40px;
    height: 40px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 50%;
    transition: background-color 0.3s ease;
}

.close-preview-btn:hover {
    background: rgba(255, 255, 255, 0.2);
}

/* 提示信息 */
.success-toast,
.error-toast {
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    padding: 16px 24px;
    border-radius: 8px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
    z-index: 1000;
    display: flex;
    align-items: center;
    gap: 8px;
    font-weight: 500;
    animation: popIn 0.3s ease-out;
    min-width: 200px;
    justify-content: center;
}

.success-toast {
    background: #28a745;
    color: white;
}

.error-toast {
    background: #dc3545;
    color: white;
}

@keyframes popIn {
    0% {
        opacity: 0;
        transform: translate(-50%, -50%) scale(0.8);
    }

    100% {
        opacity: 1;
        transform: translate(-50%, -50%) scale(1);
    }
}

.success-icon,
.error-icon {
    font-size: 18px;
    margin: 0;
}

.success-text,
.error-text {
    font-size: 14px;
    font-weight: 500;
    margin: 0;
}

/* 删除确认弹窗 */
.confirm-overlay {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.5);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 1001;
    /* animation: fadeIn 0.1s ease-out; */
}

.confirm-dialog {
    background: white;
    border-radius: 12px;
    min-width: 320px;
    max-width: 90%;
    overflow: hidden;
    box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
    /* animation: popIn 0.1s ease-out; */
}

.confirm-header {
    padding: 20px 20px 0 20px;
    text-align: center;
}

.confirm-title {
    font-size: 18px;
    font-weight: 600;
    color: #333;
    margin: 0;
}

.confirm-body {
    padding: 20px;
    text-align: center;
}

.confirm-message {
    font-size: 16px;
    color: #666;
    line-height: 1.5;
    margin: 0;
}

.confirm-footer {
    display: flex;
    border-top: 1px solid #e5e5e5;
}

.cancel-btn,
.confirm-btn {
    flex: 1;
    padding: 16px;
    border: none;
    font-size: 16px;
    font-weight: 500;
    cursor: pointer;
    transition: background-color 0.3s ease;
}

.cancel-btn {
    background: #f8f9fa;
    color: #666;
    border-right: 1px solid #e5e5e5;
}

.cancel-btn:hover {
    background: #e9ecef;
}

.confirm-btn {
    background: #ffaa00;
    color: white;
}

.confirm-btn:hover {
    background: #0056b3;
}

@keyframes fadeIn {
    from {
        opacity: 0;
    }

    to {
        opacity: 1;
    }
}
</style>